package com.lzx.iteam.util;

import android.webkit.CookieSyncManager;
import org.apache.http.cookie.Cookie;
import org.apache.http.cookie.CookieOrigin;
import org.apache.http.cookie.MalformedCookieException;
import org.apache.http.impl.cookie.RFC2109Spec;
import org.apache.http.message.BasicHeader;

import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

public class HttpClientCookieStoreProxy implements org.apache.http.client.CookieStore {

    private static TimeZone timezone = TimeZone.getTimeZone("GMT");
    private static final SimpleDateFormat httpExpiryDateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
    public static final SimpleDateFormat systemExpiryDateFormatter = new SimpleDateFormat("EEE,dd-MMM-yyyy HH:mm:ss 'GMT'", Locale.US);
    static {
        httpExpiryDateFormatter.setTimeZone(timezone);
        systemExpiryDateFormatter.setTimeZone(timezone);
    }


    private android.webkit.CookieManager webkitCookieManager;
    private String cUrl;

    public HttpClientCookieStoreProxy(String url)
    {
        webkitCookieManager = android.webkit.CookieManager.getInstance();
        cUrl = url;

    }

    @Override
    public void addCookie(Cookie cookie)  {
        //HACK: Work around weird version-only cookies from cookie formatter.
        if (cookie.getName() == "$Version")
            return;

        String cookieString = cookie.getName() + "=" + cookie.getValue();
        String domain = cookie.getDomain();
        if (domain == null) {
            return;
        }

        domain = domain.replaceAll(".*\\.(?=.*\\.)", "") ;
        cookieString += "; domain=" + domain;

        String path = cookie.getPath();
        Date expiryDate = cookie.getExpiryDate();
        boolean secure = cookie.isSecure();
        if (path != null) {
            cookieString += "; path=" + path;
        }
        if (expiryDate != null) {
            cookieString += "; expires=" + systemExpiryDateFormatter.format(expiryDate);
        }
        if (secure) {
            cookieString += "; secure";
        }
        webkitCookieManager.setCookie(domain, cookieString);
        CookieSyncManager.getInstance().startSync();
    }

    @Override
    public List<Cookie> getCookies() {

        RFC2109Spec cookieSpec = new RFC2109Spec();
        String rawCookieHeader = null;
        try{
            URL parsedURL = new URL(cUrl);

            String domain = parsedURL.getHost();

            domain = domain.replaceAll(".*\\.(?=.*\\.)", "") ;

            //Extract Set-Cookie header value from Android app CookieManager for this URL
            rawCookieHeader = webkitCookieManager.getCookie(domain);
            if(rawCookieHeader == null) return new ArrayList<Cookie>();

            //Convert Set-Cookie header value into Cookies w/in HttpClient CookieManager
            int port = parsedURL.getPort() == -1?
                    parsedURL.getDefaultPort() : parsedURL.getPort();

            CookieOrigin cookieOrigin = new CookieOrigin( domain,
                    port,
                    "/",
                    false);
            List<Cookie> appCookies = cookieSpec.parse(
                    new BasicHeader("set-cookie", rawCookieHeader),
                    cookieOrigin);

            return appCookies;
        } catch(MalformedURLException e) {

        } catch(MalformedCookieException e) {

        }
        return new ArrayList<Cookie>();
    }

    @Override
    public boolean clearExpired(Date date) {
        webkitCookieManager.removeExpiredCookie();
        return true;
    }

    @Override
    public void clear() {
        webkitCookieManager.removeAllCookie();
    }

}
